package com.learn.chapter03.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 第 3 章 配置
 *   3.1.2 properties 配置文件
 *  《深入浅出 Mybatis 技术原理与实战》—— P39
 *  https://www.cnblogs.com/tanghaorong/p/13922400.html#_label1
 */
public class SqlSessionUtil {
  private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;
  private static SqlSessionFactory sqlSessionFactory = null;

  public static SqlSessionFactory getSqlSessionFactoryByXml() {

    synchronized (CLASS_LOCK) {
      if (null != sqlSessionFactory) {
        return sqlSessionFactory;
      }
      String resource = "chapter03/mybatis-conf.xml";
      InputStream inputStream;
      InputStream is = null;
      try {
        // 加载数据库配置文件
        is = Resources.getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(is);

        // 获取加密信息
        String password= properties.getProperty("password");

        // 解密用户名和密码，并重置属性
        properties.setProperty("password", CyperTool.decodeByBase64(password));

        // 读取 mybatis 配置文件
        inputStream = Resources.getResourceAsStream(resource);
        // 通过 SqlSessionFactoryBuilder 类的 builder 方法进行构建，并使用程序传递的方式覆盖原有属性
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, properties);
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
      return sqlSessionFactory;
    }
  }

}
